<template>
	<view>
		<view class="custom-navbar">
			<!-- 左侧部分不变 -->
			<view class="left mine-header">
				<view class="icon">
					<svg width="100" height="40" viewBox="0 0 199 40" fill="none" xmlns="http://www.w3.org/2000/svg">
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M51.337 28.9604C46.9876 28.9604 43.7734 25.5534 43.7734 21.3687C43.7734 17.1839 46.9876 13.6934 51.364 13.6934C54.1358 13.6934 55.8534 14.7192 57.2111 16.2157L55.1334 18.4592C54.1076 17.3792 53.0276 16.631 51.337 16.631C48.8981 16.631 47.1252 18.7369 47.1252 21.3134C47.1252 23.9451 48.9264 26.051 51.5028 26.051C53.0828 26.051 54.2464 25.3028 55.2993 24.2228L57.3217 26.2169C55.8817 27.8239 54.1911 28.9604 51.337 28.9604"
							fill="white" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M63.6838 28.9603H60.332V13.7214H63.6838V17.2956C64.5979 15.1061 66.2885 13.6097 68.865 13.7214V17.2685H68.6709C65.7344 17.2685 63.6838 19.1803 63.6838 23.0591V28.9603Z"
							fill="white" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M86.4142 13.6934L79.006 33.0628H75.6071L77.226 28.9651L70.8789 13.6934H74.453L78.7836 24.9734L82.9413 13.6934H86.4142Z"
							fill="white" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M96.306 16.6028C94.0342 16.6028 92.0389 18.4592 92.0389 21.3134C92.0389 24.1675 94.0342 26.0228 96.306 26.0228C98.606 26.0228 100.49 24.2228 100.49 21.3134C100.49 18.431 98.5778 16.6028 96.306 16.6028M97.0813 28.9322C94.6719 28.9322 93.1472 27.7134 92.1213 26.3557V33.0616H88.7695V13.6934H92.1213V16.4357C93.2025 14.9122 94.7272 13.6934 97.0813 13.6934C100.545 13.6934 103.898 16.4357 103.898 21.3134C103.898 26.1898 100.573 28.9322 97.0813 28.9322"
							fill="white" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M111.246 16.8803V24.0544C111.246 25.3556 111.907 25.8815 113.046 25.8815H114.361V28.8756H112.068C109.628 28.8685 107.894 27.7838 107.894 24.5803V16.8803H106.033V14.0015H107.894V9.98267H111.246V14.0015H114.361V16.8803H111.246Z"
							fill="white" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M124.966 16.6305C122.278 16.6305 120.56 18.7364 120.56 21.3129C120.56 23.9176 122.416 26.0505 125.021 26.0505C127.735 26.0505 129.454 23.9458 129.454 21.3682C129.454 18.7635 127.598 16.6305 124.966 16.6305M124.966 28.9599C120.505 28.9599 117.207 25.5529 117.207 21.3682C117.207 17.1564 120.532 13.6929 125.021 13.6929C129.509 13.6929 132.807 17.1011 132.807 21.3129C132.807 25.4976 129.481 28.9599 124.966 28.9599"
							fill="white" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M138.943 25.8853V27.5747C138.943 27.6465 138.907 27.7112 138.845 27.7441L137.383 28.5888C137.321 28.6241 137.246 28.6241 137.189 28.5888L135.723 27.7441C135.664 27.7112 135.625 27.6465 135.625 27.5747V25.8853C135.625 25.8171 135.664 25.7524 135.723 25.7159L137.189 24.8712C137.246 24.8359 137.321 24.8359 137.383 24.8712L138.845 25.7159C138.907 25.7524 138.943 25.8171 138.943 25.8853"
							fill="white" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M164.858 16.6305C162.17 16.6305 160.453 18.7364 160.453 21.3129C160.453 23.9176 162.309 26.0505 164.914 26.0505C167.628 26.0505 169.345 23.9458 169.345 21.3682C169.345 18.7635 167.49 16.6305 164.858 16.6305M164.858 28.9599C160.397 28.9599 157.1 25.5529 157.1 21.3682C157.1 17.1564 160.424 13.6929 164.914 13.6929C169.402 13.6929 172.7 17.1011 172.7 21.3129C172.7 25.4976 169.374 28.9599 164.858 28.9599"
							fill="white" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M149.15 28.9432C144.801 28.8597 141.653 25.3903 141.734 21.2068C141.814 17.0244 145.094 13.5962 149.47 13.6797C152.241 13.7327 153.939 14.7903 155.268 16.3127L153.147 18.5162C152.143 17.4162 151.077 16.648 149.387 16.615C146.949 16.568 145.135 18.6397 145.086 21.2162C145.035 23.848 146.796 25.988 149.372 26.0374C150.952 26.068 152.129 25.3421 153.202 24.2821L155.187 26.315C153.716 27.8938 152.005 28.9974 149.15 28.9432"
							fill="white" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M192.627 13.6934C195.814 13.6934 197.753 15.7157 197.753 19.2898V28.9604H194.402V20.3157C194.402 17.9887 193.32 16.7416 191.437 16.7416C189.609 16.7416 188.305 18.0157 188.305 20.371V28.9604H184.953V20.2875C184.953 18.0157 183.844 16.7416 181.987 16.7416C180.132 16.7416 178.857 18.1275 178.857 20.3992V28.9604H175.504V13.6934H178.857V16.2157C179.799 14.9134 181.074 13.6934 183.318 13.6934C185.424 13.6934 186.892 14.7192 187.667 16.2698C188.86 14.7192 190.411 13.6934 192.627 13.6934"
							fill="white" />

						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M0 10.7003V29.747L16.4106 39.2717L32.8176 29.747V10.7003L16.4106 1.17651L0 10.7003ZM1.44442 28.9119V11.539L16.4106 2.8484L31.3777 11.539V28.9119L16.4106 37.5989L1.44442 28.9119Z"
							fill="#FEFEFE" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M22.8405 9.39941H9.94599L8.45117 16.0083H24.3947L22.8405 9.39941Z" fill="#FEFEFE" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M12.2336 25.1033V20.7119L8.41426 18.271L4.0918 21.5008L9.98377 31.8008H12.3371L15.1207 29.1962V27.8871L12.2336 25.1033Z"
							fill="#FEFEFE" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M20.5978 17.0056H12.248L13.6547 20.6977L13.2263 24.8349H16.4085L19.6213 24.8204L19.2209 20.6977L20.5978 17.0056Z"
							fill="#FEFEFE" />
						<path fill-rule="evenodd" clip-rule="evenodd"
							d="M24.4173 18.241L20.642 20.7117V25.1031L17.7559 27.8869V29.196L20.5385 31.7717H22.8622L28.7254 21.5006L24.4173 18.241Z"
							fill="#FEFEFE" />

					</svg>
				</view>
			</view>

			<!-- 中间标题 -->
			<view>
				<view class="title">{{ nowSubAccount }}</view>
				<view class="title-n">{{ nowNetwork }}</view>
			</view>


			<!-- 右侧操作区 -->
			<view class="right">
				<image id="networkAddress" class="image-header" :src="getImg(currentNetwork)"
					@click="toggleDropdown(1)">
				</image>
				<view class="line"></view>
				<image id="language" class="image-header" src="/static/xiaotu/hedaerRight.webp"
					@click="toggleDropdown(2)"></image>
			</view>
		</view>

		<!-- 下拉菜单 - 修改为使用动态定位 -->
		<view v-if="showDropdown" class="dropdown-menu" :style="{
				    position: 'fixed',
				    top: `${triggerPosition.top}px`,
				    left: `${triggerPosition.left}px`,
				    width: `${menuWidth}px`,
				    maxHeight: `${maxHeight}px`,
				    zIndex: 9999
				  }">
			<!-- 菜单模板1-->
			<template v-if="templatetype==1">
				<view class="dropdown-arrow" :style="{ left: `${arrowPosition}px` }"></view>
				<scroll-view scroll-y class="menu-scroll">
					<view v-for="(item, index) in list" :key="index" class="menu-item"
						@click="handleNetworkSelect(item.label)">
						<text class="item-text">{{ item.label }}</text>
					</view>
				</scroll-view>
			</template>
			<!-- 菜单模板2 -->
			<template v-if="templatetype==2">
				<view class="dropdown-arrow" :style="{ left: `${arrowPosition}px` }"></view>
				<scroll-view scroll-y class="menu-scroll">
					<view v-for="lang in supportedLangs" :key="lang" class="lang-option"
						:class="{ active: currentLang === lang }" @click="selectLanguage(lang)">
						<!-- <image :src="getFlag(lang)" class="flag-icon" /> -->
						<text>{{ $t('languages.' + lang) }}</text>
					</view>
				</scroll-view>
			</template>

		</view>
	</view>
</template>

<script>
	import network from '@/src/utils/network'
	import {
		NETWORKS
	} from '@/src/config/networks';
	import detectEthereumProvider from '@metamask/detect-provider';
	import {
		updateAccount,
		globalUserInfo
	} from '@/src/utils/userInfo';
    import api from '../../http/api';
   import th from '../../src/lang/th';
	export default {
		components: {},
		props: {
			title: String, // 支持动态标题
		},
		data() {
			return {
				showDropdown: false,
				triggerPosition: {
					top: 0,
					left: 0
				}, // 动态菜单位置
				arrowPosition: 0, // 箭头位置
				list: [{
						label: 'ERC20-USDC',
						value: 'erc20_usdc'
					},
					{
						label: 'BSC-USDC',
						value: 'bsc_usdc'
					},
					{
						label: 'ERC20-USDT',
						value: 'erc20_usdt'
					},
					{
						label: 'BSC-USDT',
						value: 'bsc_usdt'
					}
				],

				// 新增：分别记录两个触发元素的位置
				triggerRect1: null,
				triggerRect2: null,
				// 新增：记录当前激活的下拉类型
				activeDropdown: 0, // 0:无, 1:网络, 2:语言
				activeType: 0, // 新增：记录当前激活的下拉类型
				templatetype: 1, //激活的下拉模板1第一个模板2第二个模板
				// 菜单宽度（单位rpx）
				menuWidth: 300,
				// 最大高度（单位rpx）
				maxHeight: 500,
				modelValue: '',

				/* 语言 */
				showSelector: false,
				currentLang: this.$i18n.locale,
				supportedLangs: ['en','de','es','nl','fr','it','zh','ru','ja'],

				// 当前状态
				currentNetwork: null,
				currentToken: null,

			}
		},
		created() {
			this.getNowNetwork();
		},
		methods: {
			//选择语言
			selectLanguage(lang) {
				this.currentLang = lang
				this.$i18n.setLang(lang)
				this.templatetype = false
				
				//设置传递后端当前语言标识
				if(lang=='zhTw'){
					this.$updateLang('tw') 
				}else if(lang=='zh'){
					this.$updateLang('zh-cn') 
				}else{
					this.$updateLang(lang)
				}
			},
			getFlag(lang) {
				// 国旗图标（使用Base64编码的小图标）
				return flags[lang] || flags['en']
			},
			getImg(network) {
				// 1. 处理null或undefined情况
				if (!this.$userInfo.nowNetwork) return '/static/xiaotu/lan.png';

				// 2. 判断支持的链
				return ['ERC20-USDC', 'ERC20-USDT'].includes(this.$userInfo.nowNetwork) ?
					'/static/xiaotu/lan.png' :
					'/static/xiaotu/huang.png';
			},
			/* 展开气泡 */
			async toggleDropdown(type) {
				this.templatetype = type;
				if (this.showDropdown) {
					this.closeDropdown();
					return;
				}

				// 获取触发元素位置
				const rect = await this.getTriggerRect(type);

				// 计算菜单位置
				const screen = uni.getSystemInfoSync();
				const menuWidthPx = uni.upx2px(this.menuWidth);

				// 计算菜单位置（居中于触发元素）
				let menuLeft = rect.left + rect.width / 2 - menuWidthPx / 2;

				// 确保不超出屏幕
				menuLeft = Math.max(10, Math.min(menuLeft, screen.windowWidth - menuWidthPx - 10));

				// 计算箭头位置（相对于菜单）
				const arrowPosition = rect.left + rect.width / 2 - menuLeft - 10;

				// 更新位置数据
				this.triggerPosition = {
					top: rect.bottom,
					left: menuLeft
				};

				this.arrowPosition = arrowPosition;
				this.showDropdown = true;

				//console.log('菜单位置:', menuLeft, '箭头位置:', arrowPosition);
			},
			//获取当前网络状态及账户信息
			async getNowNetwork() {
				try {
					const provider = await detectEthereumProvider();

					//获取网络状态
					const chainId = await provider.request({
						method: 'eth_chainId'
					});

					//  静默获取当前账户（不会弹出授权窗口）
					const accounts = await provider.request({
						method: 'eth_accounts'
					});
					// switch (chainId) {
					// 	case '0x1':
					// 		this.$updateNetwork('ERC20-USDT');
					// 		//设置币种类
					// 		this.$updateChainType('erc')
					// 		//设置链类型
					// 		this.$updateCointype('USDT') //默认USDT
					// 		break;
					// 	case '0x38':
					// 		this.$updateNetwork('BSC-USDT');
					// 		//设置币种类
					// 		this.$updateChainType('bsc')
					// 		//设置链类型
					// 		this.$updateCointype('USDT')
					// 		break;
					// 	default:
					// 		this.$updateNetwork('其他网络');
					// }

					// 检查是否有已连接的账户
					if (accounts.length > 0) {
						// let account = accounts[0].substring(0, 6) + '****' + accounts[0].substring(accounts[0].length -
						// 	7, accounts[0].length);
						this.$updateSubAccount(accounts);
					}

					//判断账号是否注册
					this.isRegister();

				} catch (error) {
					this.error = error.message
				}

			},

			//判断注册和注册
			async isRegister() {
				api.registrationCheck({
					//邀请码
					//invite: this.$tool.getUrlQueryString('u'),
					//钱包地址
					address: this.$userInfo.nowSubAccount[0],
					chaintype: this.$userInfo.chainType,
					cointype: this.$userInfo.cointype
				}).then(res => {
					if(res.code == 1){
						this.$updateIs_auth(res.data.is_auth)
					}
					//this.$root.is_auth = res.data.is_auth;
					//this.currHuobi = localStorage.getItem('HUOBI') || 'USDT'
				}).catch(err => {
					//刷新页面
					//window.location.reload();
					return;
				})
				
			},

			async handleNetworkSelect(label) {
				try {
					// 1. 确定目标网络配置
					let targetNetworkKey, tokenSymbol;
					console.log('网络切换',label)
					switch (label) {
						
						case 'ERC20-USDC':
							targetNetworkKey = 'ETH';
							tokenSymbol = 'USDC';
							//设置币种类
							this.$updateChainType('erc')
							//设置链类型
							this.$updateCointype('USDC') //默认USDT
							//存储在浏览器
							localStorage.setItem('userSettings', JSON.stringify({
							  network: 'ERC20-USDC',
							  chainType:'erc',
							  cointype: 'USDC'
							}));
							break;
						case 'BSC-USDC':
							targetNetworkKey = 'BSC';
							tokenSymbol = 'USDC';
							//设置币种类
							this.$updateChainType('bsc')
							//设置链类型
							this.$updateCointype('USDC')
							//存储在浏览器
							localStorage.setItem('userSettings', JSON.stringify({
							  network: 'BSC-USDC',
							  chainType:'bsc',
							  cointype: 'USDC'
							}));
							break;
						case 'ERC20-USDT':
							targetNetworkKey = 'ETH';
							tokenSymbol = 'USDT';
							//设置币种类
							this.$updateChainType('erc')
							//设置链类型
							this.$updateCointype('USDT') //默认USDT
							//存储在浏览器
							localStorage.setItem('userSettings', JSON.stringify({
							  network: 'ERC20-USDT',
							  chainType:'erc',
							  cointype: 'USDT'
							}));
							break;
						case 'BSC-USDT':
							targetNetworkKey = 'BSC';
							tokenSymbol = 'USDT';
							//设置币种类
							this.$updateChainType('bsc')
							//设置链类型
							this.$updateCointype('USDT')
							//存储在浏览器
							localStorage.setItem('userSettings', JSON.stringify({
							  network: 'BSC-USDT',
							  chainType:'bsc',
							  cointype: 'USDT'
							}));
							break;
						default:
							throw new Error('未知的网络选项');
					}
					//切换网络
					await network.switchNetwork(targetNetworkKey);
					//console.log('切换网络', network)

					//更新当前状态
					this.currentNetwork = NETWORKS[targetNetworkKey];
					this.currentToken = this.currentNetwork.tokens[tokenSymbol];
					this.$updateNetwork(label);
					console.log('网络切换成功', {
						network: this.currentNetwork,
						token: this.currentToken,
					});

					// 触发后续操作，连接钱包等
					this.$emit('networkChanged', {
						network: this.currentNetwork,
						token: this.currentToken,
					});
					
					//判断账号是否注册
					this.isRegister();


				} catch (error) {
					console.error('网络切换失败:', error);
					uni.showToast({
						title: `切换失败: ${error.message}`,
						icon: 'none'
					});
				}

				this.closeDropdown()
			},
			getTriggerRect(type) {
				return new Promise(resolve => {
					const query = uni.createSelectorQuery().in(this)
					query.select(type == 1 ? '#networkAddress' : '#language').boundingClientRect(data => {
						resolve(data)
					}).exec()
				})
			},
			closeDropdown() {
				this.showDropdown = false
			},
		},
		mounted() {

			// 监听语言变化
			uni.$on('language-changed', (lang) => {
				this.currentLang = lang
			})
		},
		beforeDestroy() {
			uni.$off('language-changed')
		},
		computed: {
			//账户
			nowSubAccount() {
				if (!this.$userInfo.nowSubAccount) {
					return
				}
				let account = this.$userInfo.nowSubAccount[0].substring(0, 6) + '****' + this.$userInfo.nowSubAccount[0]
					.substring(this.$userInfo.nowSubAccount[0].length -
						7, this.$userInfo.nowSubAccount[0].length);
				return account;
			},
			//网络
			nowNetwork() {
				return this.$userInfo.nowNetwork
			},
			menuStyle() {
				// 根据当前激活的下拉类型获取对应的位置数据
				const rect = this.activeDropdown === 1 ? this.triggerRect1 :
					this.activeDropdown === 2 ? this.triggerRect2 : null;

				if (!rect) return {};

				const screen = uni.getSystemInfoSync();
				const menuWidth = uni.upx2px(this.menuWidth);

				// 计算菜单位置
				let left = rect.left + rect.width / 2 - menuWidth / 2;

				// 确保不超出屏幕
				left = Math.max(10, Math.min(left, screen.windowWidth - menuWidth - 10));

				return {
					width: menuWidth + 'px',
					maxHeight: uni.upx2px(this.maxHeight) + 'px',
					top: rect.bottom + 'px',
					left: left + 'px',
					position: 'fixed'
				}
			},

			arrowStyle() {
				// 根据当前激活的下拉类型获取对应的位置数据
				const rect = this.activeDropdown === 1 ? this.triggerRect1 :
					this.activeDropdown === 2 ? this.triggerRect2 : null;

				if (!rect) return {};

				return {
					// 箭头定位在菜单顶部中心
					left: '50%',
					transform: 'translateX(-50%)'
				}
			},
		},
	}
</script>

<style scoped>
	/* 语言 */
	.language-selector {
		position: fixed;
		top: 60px;
		right: 20px;
		z-index: 100;
	}

	.current-lang {
		background: white;
		border-radius: 20px;
		padding: 8px 16px;
		display: flex;
		align-items: center;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		cursor: pointer;
	}

	.flag-icon {
		width: 24px;
		height: 18px;
		margin-right: 8px;
		border-radius: 2px;
	}

	.lang-options {
		position: absolute;
		top: 45px;
		right: 0;
		background: white;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
		min-width: 180px;
		overflow: hidden;
		z-index: 101;
	}

	.lang-option {
		padding: 12px 16px;
		display: flex;
		align-items: center;
		border-bottom: 1px solid #eee;
		cursor: pointer;
	}

	.lang-option:last-child {
		border-bottom: none;
	}

	.lang-option:hover {
		background-color: #f5f7fa;
	}

	.lang-option.active {
		background-color: #eef5ff;
		color: #2979ff;
		font-weight: bold;
	}

	/* 顶部导航 */
	.custom-navbar {
		height: 44px;
		/* 导航栏内容高度 */
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #000000;
		color: #ffffff;
		z-index: 1000;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.left,
	.right {
		padding: 0 15px;
		display: flex;
		align-items: center;
	}

	.title {
		font-size: 15px;
		/* font-weight: bold; */
	}

	.title-n {
		font-size: 12px;
		text-align: center;
	}

	.icon {

		display: flex;
		align-items: center;
	}

	.icon-left {
		margin-left: 10rpx;
	}

	.line {
		width: 2rpx;
		height: 50rpx;
		background-color: #ffffff;
		margin: 0 20rpx;
	}

	.image-header {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50rpx;
	}



	/* 气泡 */
	.dropdown-menu {
		background: #fff;
		border-radius: 8rpx;
		box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.12);
		overflow: visible;
		margin-top: 20rpx;
	}

	.menu-scroll {
		max-height: 100%;
	}

	.dropdown-arrow {
		position: absolute;
		top: -16rpx;
		width: 0;
		height: 0;
		border-left: 16rpx solid transparent;
		border-right: 16rpx solid transparent;
		border-bottom: 16rpx solid #fff;
		filter: drop-shadow(0 -2rpx 1rpx rgba(0, 0, 0, 0.1));
		z-index: 10000;
		
	}

	/* 菜单项 */
	.menu-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 24rpx;
		min-height: 80rpx;
		box-sizing: border-box;
		transition: opacity 0.3s, transform 0.3s;
		transform-origin: top center;
		
	}

	.item-text {
		font-size: 28rpx;
		color: #333;
	}

	.menu-item:active:not(.disabled) {
		background-color: #f5f7fa;
	}

	.menu-item.active {
		background-color: #f8faff;
	}
</style>